package com.retailcloud.inventoryservice.controller;

import java.util.Map;

import com.retailcloud.commonutils.annotation.SysLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.retailcloud.inventoryservice.entity.ProductCategoryEntity;
import com.retailcloud.inventoryservice.service.ProductCategoryService;
import com.retailcloud.commonutils.utils.PageUtils;
import com.retailcloud.commonutils.utils.R;

/**
 * 商品分类表
 *
 * @author wudi
 * @email 632132852@qq.com
 * @date 2024-11-05 21:41:03
 */
@RestController
@RequestMapping("/productcategory")
public class ProductCategoryController {
    @Autowired
    private ProductCategoryService productCategoryService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = productCategoryService.queryPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        try {
            ProductCategoryEntity productCategory = productCategoryService.getCategoryById(id);
            return R.ok().put("productCategory", productCategory);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 保存
     */
    @SysLog("新增商品分类")
    @PostMapping("/save")
    public R save(@RequestBody ProductCategoryEntity productCategory) {
        try {
            productCategoryService.saveCategory(productCategory);
            return R.ok();
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 修改
     */
    @SysLog("修改商品分类")
    @PostMapping("/update")
    public R update(@RequestBody ProductCategoryEntity productCategory) {
        try {
            productCategoryService.updateCategory(productCategory);
            return R.ok();
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 删除
     */
    @SysLog("删除商品分类")
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        try {
            productCategoryService.deleteCategories(ids);
            return R.ok();
        } catch (IllegalStateException e) {
            // 业务逻辑错误（比如分类下有商品）
            return R.error(400, e.getMessage());
        } catch (IllegalArgumentException e) {
            // 参数错误
            return R.error(400, e.getMessage());
        } catch (Exception e) {

            return R.error(500, "删除分类失败");
        }
    }
}
